#include "system.h"

void fldrv_i2c_init(void)
{
	 gpio_init_type gpio_init_struct;
  /* enable the button clock */
  crm_periph_clock_enable(I2C_GPIO_CRM_CLK, TRUE);

  /* set default parameter */
  gpio_default_para_init(&gpio_init_struct);

   /* configure the I2C gpio */
  gpio_init_struct.gpio_drive_strength = GPIO_DRIVE_STRENGTH_STRONGER;
  gpio_init_struct.gpio_out_type  = GPIO_OUTPUT_PUSH_PULL;
  gpio_init_struct.gpio_mode = GPIO_MODE_OUTPUT;
  gpio_init_struct.gpio_pins = I2C_SDA_PIN | I2C_SCL_PIN;
  gpio_init_struct.gpio_pull = GPIO_PULL_NONE;
  gpio_init(I2C_SDA_GPIO, &gpio_init_struct);
	
	SCL_PIN_H;
	SDA_PIN_H;
}

static void fldrv_i2c_delay(void)
{
    uint8_t i;
    for (i = 0; i < 20; i++);
}

static void I2CStart(void)
{
	SDA_PIN_H;			//先将SDA=1，以准备在SCL=1时，将SDA=0
	SCL_PIN_H;			//时钟总线拉高
	fldrv_i2c_delay();
	SDA_PIN_L;			//SCL=1时，将SDA拉低即产生启动信号
	fldrv_i2c_delay();
	SCL_PIN_L;			//将SCL=0，完成启动信号操作
	fldrv_i2c_delay();
}

static void I2CStop(void)
{
	fldrv_i2c_delay();
	SCL_PIN_L;
	SDA_PIN_L;			//先将SDA=0，以准备在SCL=1时，将SDA=1
	fldrv_i2c_delay();
	SCL_PIN_H;			//时钟总线拉高
	SDA_PIN_H;			//SCL=1时，将SDA拉高即产生停止信号
	fldrv_i2c_delay();
}

static unsigned char I2CReadByte(void)
{
	uint8_t i,data;
	SDA_SET_INPUT;
	fldrv_i2c_delay();
	SCL_PIN_L;
	fldrv_i2c_delay();
	data = 0;
	for(i = 0; i < 8; i++)
	{
		SCL_PIN_H;
		fldrv_i2c_delay();
		data <<= 1;
		if(READ_SDA_DATA) data |= 0x1;
		
		SCL_PIN_L;
		fldrv_i2c_delay();
	}
	
	SDA_SET_OUTPUT;
	
	SDA_PIN_H;			//是否需要更多的数据
	
	fldrv_i2c_delay();
	SCL_PIN_H;
	fldrv_i2c_delay();
	SCL_PIN_L;
	fldrv_i2c_delay();
	return data;
}

static void I2CReadAck(void)
{
	uint16_t delay_Cnt;
	SDA_PIN_H;
	SDA_SET_INPUT;			//置为输入口接收应答信号
	fldrv_i2c_delay();
	SCL_PIN_H;			//做个上升沿准备读应答信号
	fldrv_i2c_delay();
	
	delay_Cnt = 0;
	while(READ_SDA_DATA)
	{
		delay_Cnt++;
		if(delay_Cnt > 500)
		{
		  break;
		}
		
	}
	SCL_PIN_L;
	SDA_SET_OUTPUT;
}

static void fldrv_i2c_write(char data)
{
	uint8_t i = 8;
	do
	{
		SCL_PIN_L;
		fldrv_i2c_delay();
		if(data&0x80)
			SDA_PIN_H;
		else
			SDA_PIN_L;
		fldrv_i2c_delay();
		SCL_PIN_H;		//时钟线做一个上升沿，将一位数据写入
		fldrv_i2c_delay();
		data <<= 1;
	}
	while(--i);
	SCL_PIN_L;
	fldrv_i2c_delay();
}

/*
SC7A20向寄存器写一个字节
RAddr：寄存器地址
WData：数据
*/
void fldrv_i2c_write_byte(uint8_t RAddr, uint8_t WData)
{
 	I2CStart();
	fldrv_i2c_write(ENS210_I2C_WADDR);
	I2CReadAck();
	fldrv_i2c_write(RAddr);
	I2CReadAck();	
	fldrv_i2c_write(WData);
	I2CReadAck();
	I2CStop();
}

/*
SC7A20从寄存器读一个字节
RAddr：寄存器地址
RData：接收数据地址
*/
void fldrv_i2c_read_byte(uint8_t RAddr, uint8_t *RData)
{
	I2CStart();
	fldrv_i2c_write(ENS210_I2C_WADDR);
	I2CReadAck();
	fldrv_i2c_write(RAddr);
//	SDA_PIN_H;			//先将SDA=1，以准备在SCL=1时，将SDA=0
//	SDA_PIN_L;			//SCL=1时，将SDA拉低即产生启动信号
	I2CReadAck();
	I2CStart();
	fldrv_i2c_write(ENS210_I2C_RADDR);
	I2CReadAck();
	*RData = I2CReadByte();
	//I2CReadAck();
	I2CStop();
}


